﻿using JT808.Protocol.Extensions.JTActiveSafety.Metadata;
using JTActiveSafety.Gateway.Models;
using JTActiveSafety.Protocol;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace JTActiveSafety.Gateway.Services
{
    ///// <summary>
    ///// 默认存储方式，数据内存缓存，接收完整时写入磁盘存储。
    ///// 警告：只能用于测试，数据可能丢失，不支持断点续传
    ///// </summary>
    //public class DefaultFileSaveService : IAttachFileStorageService
    //{
    //    private static readonly string root = "E:\\AttachFile";

    //    private readonly ILogger _logger;
    //    private readonly IAttachFileRecvService _attachFileRecvHandler;
    //    private readonly IList<JTActiveSafetyPackage> DataPackages = new List<JTActiveSafetyPackage>();

    //    public DefaultFileSaveService(ILogger<DefaultFileSaveService> logger, IAttachFileRecvService attachFileRecvHandler)
    //    {
    //        _logger = logger;
    //        _attachFileRecvHandler = attachFileRecvHandler;
    //    }

    //    public string WriteData(string terminalPhoneNo, ReadOnlySpan<byte> span)
    //    {
    //        var activeSafetyPackage = JTActiveSafetySerializer.Deserialize(span);
    //        _logger.LogWarning($"写入附件文件数据块：{activeSafetyPackage.Offset} {activeSafetyPackage.Length}");
    //        DataPackages.Add(activeSafetyPackage);
    //        return activeSafetyPackage.FileName;
    //    }

    //    public bool CheckFileIntegrity(string fileName)
    //    {
    //        uint fileSize;
    //        var cache = _attachFileRecvHandler as IAttachFileRecvRecoredManage;
    //        fileSize = cache.GetFileSize(fileName);
    //        if (fileSize <= 0)
    //        {
    //            _logger.LogWarning($"写入附件文件时出错，当前会话未找到文件名为{fileName}的缓存记录。"); // +                                                           // $"该错误通常发生在附件接收服务器刚重启后的一段时间，产生原因为上次停止服务时会话缓存未保存，建议将缓存持久化。") ;
    //            return false;
    //        }

    //        var result = new List<Node>();
    //        var fileRecvItems = DataPackages.Where(c => c.FileName == fileName).Select(c => new Node() { Offset = c.Offset, Length = c.Length }).ToList();
    //        if (CheckLinkedListMissingNodes.TryCheck(fileRecvItems, fileSize, ref result))
    //        {
    //            if (result.Count == 0)
    //                return true;
    //        }
    //        _logger.LogWarning($"检查文件完整性时发生异常：{fileName} size-{fileSize}");
    //        return false;
    //    }
    //    public Task SaveFile(string terminalPhoneNo, string fileName)
    //    {
    //        Task.Factory.StartNew(() =>
    //        {
    //            var fileInfo = new AttachFileName(terminalPhoneNo, fileName);
    //            if (fileInfo.IsValid)
    //            {
    //                var Data = DataPackages.Where(c => c.FileName == fileName).OrderBy(c => c.Offset).ToList();
    //                OnSaveFile(Data, fileInfo);
    //            }
    //        });
    //        return Task.CompletedTask;
    //    }

    //    private void OnSaveFile(List<JTActiveSafetyPackage> data, AttachFileName fileInfo)
    //    {
    //        var Data = data;//.OrderBy(c => c.Offset).ToList();
    //        try
    //        {
    //            var path = Path.Combine(root, fileInfo.Date, fileInfo.TerminalPhoneNo, fileInfo.AlarmCode + "_" + fileInfo.SN, fileInfo.Time);
    //            if (!Directory.Exists(path))
    //            {
    //                Directory.CreateDirectory(path);
    //            }

    //            var fileFullName = Path.Combine(path, fileInfo.FileName);

    //            using var writer = new BinaryWriter(File.Open(fileFullName, FileMode.OpenOrCreate));
    //            foreach (var item in Data)
    //            {
    //                _logger.LogWarning($"写入附件文件{fileInfo.FileName} 偏移-{item.Offset} 长度-{item.Length} 结尾-{item.Offset + item.Length}");
    //                writer.Seek((int)item.Offset, SeekOrigin.Begin);
    //                writer.Write(item.Bodies);
    //                DataPackages.Remove(item);
    //            }
    //            writer.Flush();
    //            writer.Close();
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex, "接收附件文件时写入文件出错！");
    //        }
    //        finally
    //        {
    //            var cache = _attachFileRecvHandler as IAttachFileRecvRecoredManage;
    //            cache.ClearFileCache(fileInfo.FileName);
    //        }
    //    }

    //}


}
